/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package poetry.parser

import scala.xml._
import dtd._

object PoetryXMLParser {
  val poetryDb = new PoetryDatabase(Nil)

  def parse(content: Node) = content match {
    case <leksebi>{ contents @ _* }</leksebi> => contents.map( x => parsePoetry(x) ).toList
  }

  def parsePoetry(content: Node) = content match {
    case <leksi>{ contents @ _* }</leksi> =>
      new Poetry((content \ "@saxeli").text, contents.map( x => parseStrophe(x) ).toList)
  }

  def parseStrophe(content: Node) = content match {
    case <strofi>{ contents @ _* }</strofi> => new Strophe( contents.map( x => x.text ).toList )
  }

  def readFile(path: String) = try {
    poetryDb.poetry = parse(XML.loadFile(path))
    PoetryPublisher.publish(PoetryDbChanged)
    Some(poetryDb.poetry.head)
  } catch {
    case e: Exception =>
      (new poetry.gui.MyMessage("ვერ ვხსნი ფაილს: "+ path + "\n\n" + "შეცდომა:" + e.toString )).open
      None
  }

  def writeFile(path: String) = try {
    val output = <leksebi>{ poetryDb.poetry.map( x => export(x.name, x.body)) }</leksebi>
    val docType = DocType("leksebi", SystemID("poetry.dtd"), Nil)
    XML.save(path+".xml", output, "UTF-8", true, docType)
    PoetryPublisher.publish(ChangesSaved)
  } catch {
    case e: Exception =>
      (new poetry.gui.MyMessage("ვერ ვინახავ ფაილს: "+ path + "\n\n" + "შეცდომა:" + e.toString )).open
  }

  def export(name: String, body: List[Strophe]) =
    <leksi saxeli={ name } >
      { body.map( x =>
      <strofi> {
        x.body.map ( y => <strikoni> { y } </strikoni> )
      } </strofi> ) }
    </leksi>
}

